package nafos.security.auth

import nafos.security.Auth
import nafos.security.Security
import nafos.security.SecurityController
import nafos.server.NafosRunner
import nafos.server.SpringApplicationContextHolder
import org.springframework.stereotype.Component
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping


/**
 *@ClassName HandlerMappingAuthManager
 *@Description 应用种路由的权限系统
 *@Author hxy
 *@Date 2020/5/15 17:29
 */
@Component
class HandlerMappingAuthManager : NafosRunner {

    companion object {
        val ROUTE_AUTH_MAPPING = HashMap<String, String>()
        const val ONLY_LOGIN_TYPE = "NAFOS@SECURITY"
    }


    override fun run(vararg args: String?) {
        if (!SpringApplicationContextHolder.getContext()!!.containsBean("requestMappingHandlerMapping")){
            return
        }
        val mapping = SpringApplicationContextHolder.getSpringBeanForClass(RequestMappingHandlerMapping::class.java)!!
        val requestHandlerMethods = mapping.handlerMethods
        requestHandlerMethods.forEach { (t, u) ->
            val url = t.patternsCondition.patterns
            var auth = u.method.getAnnotation(Auth::class.java)
            if (auth != null) {
                url.forEach {
                    ROUTE_AUTH_MAPPING[it] = auth.value
                }
            } else {
                val security = u.method.getAnnotation(Security::class.java)
                val securityController = u.beanType.getAnnotation(SecurityController::class.java)
                if (security != null || securityController != null) {
                    url.forEach {
                        ROUTE_AUTH_MAPPING[it] = ONLY_LOGIN_TYPE
                    }
                }
            }
        }
    }
}